<?php

define('MAX_RANK', 26);
define('MY_EMAIL_ADDRESS', 'panos1962@gmail.com');

if (isset($no_session)) {
	$_SESSION = array();
	if (isset($_REQUEST) && is_array($_REQUEST) &&
		array_key_exists('login', $_REQUEST)) {
		$_SESSION['tl_login'] = $_REQUEST['login'];
	}
}
else {
	// 24 * 7 * 3600 = 604800
	ini_set('session.gc_maxlifetime', '604800');
	session_set_cookie_params(604800);
	session_start();
}
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

global $globals;
unset($globals);

class Globals {
	public $server;
	public $time_dif;
	public $db;
	public $phpmyadmin;

	public function __construct() {
		unset($this->server);
		unset($this->time_dif);
		unset($this->db);
		unset($this->phpmyadmin);
	}

	public function is_pektis() {
		return(isset($this->pektis));
	}

	public function not_pektis() {
		return(!$this->is_pektis());
	}

	public function perastike($key) {
		return(isset($_REQUEST) && is_array($_REQUEST) &&
			array_key_exists($key, $_REQUEST));
	}

	public function perastike_check($key, $msg = NULL) {
		if ($this->perastike($key)) {
			return($_REQUEST[$key]);
		}

		$this->klise_fige(isset($msg) ? $msg : $key . ': δεν περάστηκε παράμετρος');
	}

	public function session_set($tag) {
		if ((!isset($_SESSION)) || (!is_array($_SESSION))) {
			$this->klise_fige('_SESSION: not set or not an array');
		}

		return (array_key_exists($tag, $_SESSION));
	}

	public function email_check($email, $msg = NULL) {
		if (!@filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$this->klise_fige(isset($msg) ? $msg : $email . ': invalid email address');
		}
	}

	public function asfales($s) {
		if (get_magic_quotes_gpc()) {
			$s = stripslashes($s);
		}

		if (isset($this->db)) {
			return(@mysqli_real_escape_string($this->db, $s));
		}

		return($s);
	}

	// Η μέθοδος "akirosi_script" χρησιμοποιείται για να ακυρώσει τυχόν
	// ενσωματωμένο javascript κώδικα σε μηνύματα και συζητήσεις, και
	// το επιτυγχάνει εισάγοντας χαρακτήρα μηδενικού πλάτους πριν τη
	// λέξη script.

	public function akirosi_script($s) {
		return(preg_replace("/script/i", "&#8203;script", $s));
	}

	public function sql_query($query, $msg = 'SQL error') {
		$result = @mysqli_query($this->db, $query);
		if ($result) { return($result); }

		$this->klise_fige($msg . ': ' . $query . ': ' . @mysqli_error($this->db));
	}

	// Επιχειρεί να διαβάσει μια γραμμή από αρχείο. Αν τα καταφέρει,
	// επιστρέφει τη γραμμή, αλλιώς FALSE.

	public function get_line($fh) {
		$line = fgets($fh);
		if ($line) {
			return(preg_replace("/[\r\n].*/", '', $line));
		}
		return(FALSE);
	}

	public function put_line($fh, $s) {
		return(fwrite($fh, $s . "\n"));
	}

	public function klidoma($tag, $timeout = 2) {
		$query = "SELECT GET_LOCK('" . $this->asfales($tag) . "', " . $timeout . ")";
		$result = @mysqli_query($this->db, $query);
		if (!$result) { return(FALSE); }

		$row = @mysqli_fetch_array($result, MYSQLI_NUM);
		if (!$row) { return(FALSE); }

		@mysqli_free_result($result);
		if ($row[0] != 1) { return(FALSE); }

		return(TRUE);
	}

	public function xeklidoma($tag, $commit = NULL) {
		if (isset($commit)) {
			if ($commit) {
				@mysqli_commit($this->db);
			}
			else {
				@mysqli_rollback($this->db);
			}
		}

		$query = "DO RELEASE_LOCK('" . $this->asfales($tag) . "')";
		@mysqli_query($this->db, $query);
	}

	public function klise_fige($msg = 0) {
		if (isset($this->db)) {
			@mysqli_kill($this->db, @mysqli_thread_id($this->db));
			@mysqli_close($this->db);
		}
		die($msg);
	}
}

function set_globals($anonima = FALSE) {
	global $globals;

	if (isset($globals)) {
		die('globals object redefinition');
	}

	$globals = new Globals();

	if ((!isset($_SERVER)) || (!is_array($_SERVER))) {
		die('_SERVER: not set or not an array');
	}

	$dbhost = 'localhost';
	$dpass = preg_replace('/[^a-zA-Z0-9]/', '', '@p#a@$r*%09##o c$$#@!t@..:');
	switch ($_SERVER['SERVER_NAME']) {
	case '127.0.0.1':
		$globals->server = 'http://127.0.0.1/tetralat/';
		$dbname = 'tetralat';
		$dbuser = 'root';
		$dbpassword = '';
		$globals->phpmyadmin = 'http://127.0.0.1/phpmyadmin/index.php?db=tetralat';
		break;
	case 'localhost':
		$globals->server = 'http://localhost/tetralat/';
		$dbname = 'tetralat';
		$dbuser = 'root';
		$dbpassword = '';
		$globals->phpmyadmin = 'http://127.0.0.1/phpmyadmin/index.php?db=tetralat';
		break;
	case '78.47.123.119':
	case 'opasopa.net':
	case 'www.opasopa.net':
		$globals->server = 'http://www.opasopa.net/tetralat/';
		break;
	case 'tetralat.orgfree.com':
		$globals->server = 'http://' . $_SERVER['SERVER_NAME'] . '/';
		$dbname = '441575';
		$dbuser = '441575';
		$dbpassword = $dpass;
		break;
	default:
		die($_SERVER['SERVER_NAME'] . ': unknown server');	
	}

	if ($anonima) {
		return;
	}

return;
	$globals->db = @mysqli_connect($dbhost, $dbuser, $dbpassword);
	if (!$globals->db) {
		die('database connection failed (' .
			@mysqli_connect_error() . ')');
	}

	@mysqli_set_charset($globals->db, 'UTF8');
	if (!@mysqli_select_db($globals->db, $dbname)) {
		$globals->klise_fige('cannot open database (' . $dbname . ')');
	}
}

function set_pektis() {
	global $globals;

	$globals->pektis = NULL;
	if (!$globals->session_set('tl_login')) {
		return;
	}

	$globals->pektis = new Pektis($_SESSION['tl_login']);
	if (!isset($globals->pektis->login)) {
		$globals->pektis = NULL;
		return;
	}
}

class Page {
	public static function stylesheet($css) {
		global $globals;
		?>
		<link rel="stylesheet" type="text/css" href="<?php
			print $globals->server . $css; ?>.css" />
		<?php
	}

	public static function javascript($script) {
		global $globals;
		?>
		<script type="text/javascript" src="<?php
			print $globals->server . $script; ?>.js"></script>
		<?php
	}

	public static function head($titlos = 'TetraLat') {
		global $globals;

		header('Content-Type: text/html; charset=UTF-8');
		?>
		<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
				"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="description" content="TetraLat -- Check your skills in solving latin squares" />
		<meta name="keywords" content="latin square,latin squares,latin,square" />
		<meta name="author" content="Panos Papadopoulos" />

		<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="<?php
			print $globals->server; ?>favicon.ico" />
		<title><?php print $titlos; ?></title>
		<?php self::stylesheet('lib/standard'); ?>
		<script type="text/javascript">
		//<![CDATA[
		var globals = {};
		globals.server = '<?php print $globals->server; ?>';
		globals.timeDif = <?php print time(); ?>;
		globals.paraskinio = {};
		globals.paraskinio.index = <?php print $globals->session_set('tl_paraskinio') ?
			$_SESSION['tl_paraskinio'] : 0; ?>;
		<?php
		if ($globals->session_set('tl_login')) {
			?>
			globals.pektis = '<?php print $_SESSION['tl_login']; ?>';
			<?php
		}
		if ($globals->session_set('ps_whlt') &&
			preg_match('/^[0-9]+:[0-9]+:[0-9]+:[0-9]+$/', $_SESSION['ps_whlt'])) {
				?>
				globals.funchatWhlt = '<?php print $_SESSION['ps_whlt']; ?>';
				<?php
		}
		?>
		//]]>
		</script>
		<?php self::javascript('lib/standard'); ?>
		<?php
	}

	public static function body() {
		?>
		</head>
		<body>
		<div id="selida" class="selida">
		<?php
	}

	public static function toolbar() {
		?>
		<div class="toolbar">
			<table class="tbldbg" style="width: 100%;"><tr>
			<td class="tbldbg" style="width: 49%;">
				<div class="toolbarLeft">
					<?php self::leftTB(); ?>
				</div>
			</td>
			<td class="tbldbg">
				<div class="toolbarCenter">
					<?php self::centerTB(); ?>
				</div>
			</td>
			<td class="tbldbg" style="width: 49%;">
				<div class="toolbarRight">
					<?php self::rightTB(); ?>
				</div>
			</td>
			</tr></table>
		</div>
		<?php
	}

	protected static function leftTB() {
	}

	protected static function centerTB($titlos = 'TetraLat') {
		print $titlos;
	}

	protected static function rightTB() {
		global $globals;

		if ($globals->is_pektis()) {
			?>
			<a target="_blank" href="<?php
				print $globals->server; ?>account/signup.php?modify"
				class="data login" title="Account data"
				style="max-width: 5.4cm; overflow: hidden;<?php
					if ($globals->pektis->login == SYSTEM_ACCOUNT) {
						print " color: #FF3333;";
					}
					?>"><?php print $globals->pektis->login; ?></a>
			<?php
			self::logout_section();
		}
		elseif (!isset($globals->klista)) {
			/*
			self::signup_section();
			self::login_section();
			*/
		}
	}

	protected static function signup_section() {
		global $globals;
		?>
		[&nbsp;<a title="Create account" href="<?php print $globals->server;
			?>account/signup.php" class="data">Sign Up</a>&nbsp;]
		<?php
	}

	protected static function login_section() {
		global $globals;
		?>
		[&nbsp;<a title="Login" href="<?php print $globals->server;
			?>account/login.php" class="data">Sign in</a>&nbsp;]
		<?php
	}

	protected static function logout_section() {
		global $globals;
		?>
		[&nbsp;<a title="Logout" href="<?php print $globals->server;
			?>index.php?logout=yes" class="data">Sign out</a>&nbsp;]
		<?php
	}

	public static function fyi_top() {
		?>
		<div id="fyiTop" class="fyi fyiTop">&nbsp;</div>
		<?php
	}

	public static function fyi_bottom() {
		?>
		<div id="fyiBottom" class="fyi fyiBottom">&nbsp;</div>
		<?php
	}

	public static function ribbon() {
		?>
		<div id="ribbon" class="ribbon">
			<table class="tbldbg" style="width: 100%;"><tr>
			<td class="tbldbg" style="width: 49%; vertical-align: top;">
				<div class="ribbonLeft">
					<?php self::leftRB(); ?>
				</div>
			</td>
			<td class="tbldbg" style="vertical-align: top;">
				<div class="ribbonCenter">
					<?php self::centerRB(); ?>
				</div>
			</td>
			<td class="tbldbg" style="width: 49%; vertical-align: top;">
				<div class="ribbonRight">
					<?php self::rightRB(); ?>
				</div>
			</td>
			</tr></table>
		</div>
		<?php
	}

	protected static function leftRB() {
		global $globals;
		?>
		<a href="http://www.gnu.org/copyleft/gpl.html" target="_blank"
			title="GNU Affero General Public License"><img
			src="<?php print $globals->server; ?>images/gplv3.png"
			alt="GNU Affero General Public License" style="height: 0.6cm;" /></a>
		<div title="For the server needs…" style="display: inline-block;">
		<form target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post">
		<input type="hidden" name="cmd" value="_s-xclick">
		<input type="hidden" name="hosted_button_id" value="M3VAQ7QDDSB3Q">
		<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif"
			border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"
			style="height: 0.64cm;">
		<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif"
			width="1" height="1">
		</form>
		</div>
		<?php
	}

	protected static function centerRB() {
	}

	protected static function rightRB() {
		global $globals;
		?>
		<div class="copyright">
			&copy; Panos I. Papadopoulos <span style="font-style: normal;">[<a
				title="Send mail to &quot;<?php print MY_EMAIL_ADDRESS; ?>&quot;"
				href="mailto:<?php print MY_EMAIL_ADDRESS; ?>"><img
				src="<?php print $globals->server; ?>images/email.png"
				style="width: 0.6cm; height: 0.5cm; margin-bottom: -0.10cm;"
					alt="" /></a>]</span> 2012&ndash;
		</div>
		<?php
	}

	public static function close($ribbon = TRUE) {
		self::ribbon();
		?>
		</div>
		</body>
		</html>
		<?php
	}

	public static function apokripsi($id) {
		global $globals;
		?>
		<div id="apokripsi<?php print $id; ?>" class="apokripsi">
			<img class="pinezaIcon" title="Καρφίτσωμα" src="<?php
				print $globals->server; ?>images/pineza.png" alt=""
				onclick="karfitsoma('<?php print $id; ?>', this);" />
			<img class="apokripsiIcon" title="Απόκρυψη" src="<?php
				print $globals->server; ?>images/Xgrey.png" alt=""
				onclick="sviseNode(getelid('<?php print $id; ?>'));" />
		</div>
		<?php
	}

	public static function json() {
		header('Content-Type: application/json; charset=UTF-8');
	}

	public static function data() {
		header('Content-type: text/plain; charset=utf-8');
	}

	public static function administrator_check() {
		global $globals;
		if (!$globals->is_administrator()) {
			?>
			<meta http-equiv="refresh" content="0; url=<?php
				print $globals->server; ?>administrator/login.php" />
			<?php
		}
	}
}

class Xronos {
	public static function pote($ts, $offset = 0, $format = 'd/m/Y, h:i', $prin = TRUE) {
		$ts += $offset;
		if ($prin) {
			$dif = time() - $ts;
			if ($dif < 60) {
				return 'τώρα';
			}

			if ($dif < 3600) {
				$x = round($dif / 60);
				return 'πριν ' . $x . ' λεπτ' . ($x < 2 ? 'ό' : 'ά');
			}

			if ($dif < 86400) {
				$x = round($dif / 3600);
				return 'πριν ' . $x . ' ώρ' . ($x < 2 ? 'α' : 'ες');
			}
		}

		return date($format, $ts);
	}
}
?>
